function register(config) {
  if ("serviceWorker" in navigator) {
    const swUrl = `${config.path}/service-worker.js?v=${config.v}`;
    registerValidSW(swUrl, config);
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      if (config && config.onRegster) {
        config.onRegster(registration);
      }

      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              console.log(
                "New content is available and will be used when all " +
                  "tabs for this page are closed. See http://bit.ly/CRA-PWA."
              );

              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              console.log("Content is cached for offline use.");

              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}

function unregister() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

function urlB64ToUint8Array(base64String) {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, "+")
    .replace(/_/g, "/");

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

register({
  onUpdate: () => {
    const event = document.createEvent("Event");
    event.initEvent("sw.update", true, true);
    event.data = { isS: false };
    window.dispatchEvent(event);
  },
  onSuccess: () => {
    const event = document.createEvent("Event");
    event.initEvent("sw.update", true, true);
    event.data = { isS: true };
    window.dispatchEvent(event);
  },
  onRegster: reg => {
    "Notification" in window &&
      Notification.requestPermission().then(result => {
        if (result === "granted") {
          const pubKey =
            "BC2kS3pBpGK9G0saEhVRJfde16KzA254DkzaH61vWtubskR4E1dzEDR47_xGdy_2og8XwvflIfj8Gl3QpVGvz24";

          reg.pushManager.getSubscription().then(scription => {
            if (scription === null) {
              reg.pushManager
                .subscribe({
                  userVisibleOnly: true,
                  applicationServerKey: urlB64ToUint8Array(pubKey)
                })
                .then(scription => {
                  const fData = new FormData();
                  fData.append("subscription", JSON.stringify(scription));
                  fData.append("add_time", "2018-1-1");

                  fetch(
                    "https://apis.cnjiaoziji.com/push-php/pomodoro.add.php",
                    {
                      method: "POST",
                      body: fData
                    }
                  );
                });
            }
          });
        }
      });
  },
  v: 48,
  path: "/qrcode-web"
});
